package ua.nure.nguyen.blinov.chapter3.variantc;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import ua.nure.nguyen.blinov.chapter3.variantb.RationalNumber;

/**
 * Определить класс Полином c коэффициентами типа Рациональная Дробь. Объявить
 * массив/список/множество из n полиномов и определить сумму полиномов массива.
 * 
 * @author Viet Nguyen
 * 
 */
public class Polynom {
	private List<RationalNumber> coeffList;

	/**
	 * Allocates new Polynom objects
	 * 
	 * @param coeffList
	 *            The coefficient list
	 */
	public Polynom(List<RationalNumber> coeffList) {
		this.coeffList = new ArrayList<RationalNumber>(coeffList);
	}

	/**
	 * Adds The Polynom object to this Polynom object
	 * 
	 * @param polynom
	 *            The Polynom object
	 * @return The sum of the Polynom objects
	 */
	public Polynom add(Polynom polynom) {
		int size1 = coeffList.size();
		int size2 = polynom.coeffList.size();
		int size = size1 > size2 ? size2 : size1;
		List<RationalNumber> newCoeffList = new ArrayList<RationalNumber>();
		for (int i = 0; i < size; i++) {
			newCoeffList.add(coeffList.get(i).add(polynom.coeffList.get(i)));
		}
		if (size1 > size2) {
			copyCoeffList(coeffList, size, size1, newCoeffList);
		} else {
			copyCoeffList(polynom.coeffList, size, size2, newCoeffList);
		}
		return new Polynom(newCoeffList);
	}

	private void copyCoeffList(List<RationalNumber> src, int startIndex,
			int endIndex, List<RationalNumber> dst) {
		for (int i = startIndex; i < endIndex; i++) {
			dst.add(src.get(i));
		}
	}

	@Override
	public String toString() {
		StringBuilder result = new StringBuilder();
		for (int i = 0; i < coeffList.size(); i++) {
			result.append(String.format(" + %s*x^%d", coeffList.get(i)
					.toFraction(), i));
		}
		result.delete(0, 2);
		return result.toString();
	}

	private static final int MAX = 20;
	private static Random random = new Random();

	/**
	 * Calls all the public methods
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Polynom p1 = new Polynom(randomRNL(10));
		System.out.println(p1);
		Polynom p2 = new Polynom(randomRNL(12));
		System.out.println(p2);
		System.out.println(p1.add(p2));
	}

	private static RationalNumber randomRN() {
		return new RationalNumber(random.nextInt(MAX) + 1,
				random.nextInt(MAX) + 1);
	}

	private static List<RationalNumber> randomRNL(int size) {
		List<RationalNumber> result = new ArrayList<RationalNumber>();
		for (int i = 0; i < size; i++) {
			result.add(randomRN());
		}
		return result;
	}
}
